﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttackEntity : MonoBehaviour
{
    private Transform attackTransform;
    private Transform characterVisual;

    private void Awake()
    {
        EventCenter.AddListener<string, float,float, float,float>(MyEventType.Attack, StartAttack);
        attackTransform = GameObject.Find("attackTransform").transform;
        characterVisual = GameObject.Find("Visual").transform;
    }

    private void Update()
    {
        if (characterVisual.localScale.x < 0)
        {
            attackTransform.localPosition = new Vector3((float)-0.327, 0, 0);
            attackTransform.localEulerAngles = new Vector3(0, 180, 0);
        }
        else
        {
            attackTransform.localPosition = new Vector3((float)0.327, 0, 0);
            attackTransform.localEulerAngles = new Vector3(0, 0, 0);
        }
    }

    void StartAttack(string attackAnimationPath,float animationTime,float attackDistance,float attackAngle,float damage)
    {
        StartCoroutine(Attack(attackAnimationPath, animationTime, attackDistance, attackAngle,damage));
    }
    IEnumerator Attack(string attackAnimationPath,float animationTime,float attackDistance,float attackAngle,float damage)
    {
        Object _attackPreb = Resources.Load(attackAnimationPath, typeof(GameObject));
        GameObject attackPreb = Instantiate(_attackPreb, attackTransform) as GameObject;
        yield return new WaitForSeconds(animationTime);
        DamageJudge(attackDistance,attackAngle,damage);
        GameObject.Destroy(attackPreb);
    }

    void DamageJudge(float attackDistance,float attackAngle,float damage)
    {
        Debug.Log("攻击距离为" + attackDistance);
        Debug.Log("攻击角度为" + attackAngle);
        Debug.Log("攻击伤害为" + damage);

        foreach (GameObject go in Data.Instance.monster)
        {
            //敌人和主角的距离
            float tempDis1 = (go.transform.position - this.transform.position).magnitude;
            Debug.Log("与" + go + "的距离为" + tempDis1);

            //计算敌人和主角的方向夹角
            Vector2 v2 = go.transform.position - this.transform.position;
            float angle = Vector2.Angle(v2, this.transform.forward);
            Debug.Log("与" + go + "的夹角为" + angle);

            if (tempDis1 < attackDistance && angle < attackAngle)
            {
                Debug.Log(go + "被攻击了，尝试造成伤害");
                EventCenter.Broadcast<GameObject, float>(MyEventType.Damage, go, damage);
            }
        }
    }

}
